package personnal.blog2pdf.reader;

import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.beans.factory.annotation.Autowired;

import personnal.blog2pdf.data.PostInfo;

public class PostInfoReader implements ItemReader<PostInfo> {

    private static final Logger logger = Logger.getLogger(PostInfoReader.class);

    @Autowired
    private WordpressClient wordpressClient;

    private DateTime currentMonth;
    private DateTime endMonth;

    private List<PostInfo> postIds;
    private Iterator<PostInfo> idIterator;

    public PostInfoReader(String fromMonth, String toMonth) {
        super();
        DateTimeFormatter dateParser = DateTimeFormat.forPattern("yyyy-MM");
        this.currentMonth = dateParser.parseDateTime(fromMonth);
        this.endMonth = dateParser.parseDateTime(toMonth).plusMonths(1);
    }

    @BeforeStep
    public void beforeStep(StepExecution stepExecution) throws Exception {
        fetchPostIds();
    }

    @Override
    public PostInfo read() throws Exception, UnexpectedInputException, ParseException {
        while (this.idIterator.hasNext() == false && this.endMonth.isAfter(this.currentMonth)) {
            fetchPostIds();
        }
        if (this.idIterator.hasNext() == false) {
            return null;
        }
        PostInfo postInfo = this.idIterator.next();
        return postInfo;
    }

    private void fetchPostIds() throws Exception {
        if (logger.isInfoEnabled()) {
            logger.info("Fetching post ids for month: " + this.currentMonth);
        }
        this.postIds = this.wordpressClient.getPostIds(this.currentMonth);
        if (logger.isDebugEnabled()) {
            logger.debug("Found " + this.postIds.size() + " posts to handle");
        }
        this.idIterator = this.postIds.iterator();
        this.currentMonth = this.currentMonth.plusMonths(1);
    }

    public void setWordpressClient(WordpressClient wordpressClient) {
        this.wordpressClient = wordpressClient;
    }
}
